package com.dudu.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.shardingsphere.driver.api.ShardingSphereDataSourceFactory;
import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.*;

@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = {"com.**.dao"}, sqlSessionFactoryRef = "sqlSessionFactory")
public class ShardingConfiguration {

    @Autowired
    private MybatisConfigurationSupport mybatisConfigurationSupport;


    @Bean(name = "primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource primaryDataSource(){
        DruidDataSource datasource = new DruidDataSource();
        return datasource;
    }

    // 不使用shardingDataSource 事务是OK的
    @Bean
    @DependsOn({ "primaryDataSource"})
    @Primary
    public DataSource shardingDataSource() {
        DataSource dataSource = null;
        ShardingRuleConfiguration shardingRuleConfig  = new ShardingRuleConfiguration();

        try {
            Properties properties = new Properties();
            properties.setProperty("sql.show", "true");
            properties.setProperty("proxy.transaction.type", "LOCAL");

            dataSource = ShardingSphereDataSourceFactory.createDataSource(this.primaryDataSource(),
                    Collections.singleton(shardingRuleConfig), properties);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return dataSource;
    }

    @Bean(name = "sqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(DataSource shardingDataSource) throws Exception {
        return mybatisConfigurationSupport.build(shardingDataSource);
    }

    @Bean
    @Primary
    public PlatformTransactionManager txManager(final DataSource shardingDataSource) {
        return new DataSourceTransactionManager(shardingDataSource);
    }
}
